package com.cloud.core.tools;

import android.content.Context;
import android.media.MediaPlayer;

import androidx.annotation.RawRes;

import java.io.IOException;
import java.util.LinkedList;

/**
 * @Author： Chen
 * @Date： 2019/7/9
 * @Desc：
 */

public class PlayVoiceManager {
    private static volatile PlayVoiceManager INSTANCE = null;
    private static LinkedList<MediaPlayer> queue = new LinkedList<>();

    private boolean isPlaying;

    private Context mContext;

    private PlayVoiceManager(Context context) {
        this.mContext = context.getApplicationContext();
    }

    /**
     * 单例
     *
     * @param context
     * @return
     */
    public static PlayVoiceManager with(Context context) {
        if (INSTANCE == null) {
            synchronized (PlayVoiceManager.class) {
                if (INSTANCE == null) {
                    INSTANCE = new PlayVoiceManager(context);
                }
            }
        }
        return INSTANCE;
    }

    public void setPlay(boolean isPlaying) {
        this.isPlaying = isPlaying;
    }

    public boolean isPlay() {
        return isPlaying;
    }

    public void play(@RawRes int playSource) {
        MediaPlayer sound = createSound(playSource);
        if (sound == null) {
            System.out.println("音频创建失败");
            return;
        }

        queue.addLast(sound);

        if (!INSTANCE.isPlay()) {
            startPlay();
        }
    }

    private void startPlay() {
        if (queue.size() == 0) {
            return;
        }
        try {
            MediaPlayer first = queue.getFirst();
            first.prepare();
            first.start();
            INSTANCE.setPlay(true);
            //播放完成触发此事件
            first.setOnCompletionListener(mp -> {
                mp.release();//释放音频资源
                INSTANCE.setPlay(false);
                queue.removeFirst();
                startPlay();
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private MediaPlayer createSound(@RawRes int playSource) {
        MediaPlayer mp = MediaPlayer.create(mContext, playSource);
        //下面这三句是控制语速，但是只适用于Android6.0 以上，以下的就会报错
//        PlaybackParams pbp = new PlaybackParams();
//        pbp.setSpeed(1.5F);
//        mp.setPlaybackParams(pbp);
        mp.stop();
        return mp;
    }
}
